package com.czkt.config;

import com.czkt.pojo.*;
import com.czkt.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class CoustUserDetailService implements UserDetailsService {

    @Autowired
    SsUserService userService;

    @Autowired
    SsUserRoleRelService userRoleRelService;

    @Autowired
    SsAuthorityRoleRelService authorityRoleRelService;

    @Autowired
    SsAuthorityService authorityService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SsUser ssUser = userService.getUserName(username);
        if (ssUser == null){
            return null;
        } else {
            List<SsUserRoleRel> userRoleRelList = userRoleRelService.getUid(ssUser.getId());
            Set<Long> roles = userRoleRelList.stream().map(list->{
                return list.getId();
            }).collect(Collectors.toSet());

            List<SsAuthorityRoleRel> authorityRoleRelList = authorityRoleRelService.getListByRid(roles);

            Set<Long> authoritySet = authorityRoleRelList.stream().map(list->{
                return list.getAuthorityId();
            }).collect(Collectors.toSet());

            List<SsAuthority> authorityList = authorityService.getListById(authoritySet);

            List<String> authorityLists = authorityList.stream().map(rolesList->rolesList.getName()).collect(Collectors.toList());

            List<GrantedAuthority> authority = authorityLists.stream().map(auth->new SimpleGrantedAuthority(auth)).collect(Collectors.toList());
            return new User(ssUser.getUsername(),new BCryptPasswordEncoder().encode(ssUser.getPassword()),authority);
        }
    }
}
